<?php

/*
 * 公司类
 */

namespace Home\Logic;

class CompanystoremapLogic {

    public function __construct() {
        $this->c = D('Company_store_map');
        import('Memcachectr');
        $this->m = \Think\Memcachectr::create();
    }

    public function getCompanyMap($user_id, $is_admin = true, $store_id = 0) {
        if ($is_admin) {
            $where = 'admin_id=' . $user_id;
        } else {
            $where = 'store_admin_id=' . $user_id;
        }
        if ($store_id > 0) {
            $where .= ' and store_id=' . $store_id;
        }
        return $this->c->where($where)->select();
    }

    public function insertCompanyMap($admin_id, $store_admin_id, $store_id, $cn = false) {
        if ($cn == false) {
            $cn = $this->createNumber();
        }
        $data['company_number'] = $cn;
        $data['admin_id'] = $admin_id;
        $data['store_admin_id'] = $store_admin_id;
        $data['store_id'] = $store_id;
        $re = $this->c->add($data);
        if ($re) {
            return $cn;
        }
        return false;
    }

    public function getStoreIds($admin_id) {
        $company = $this->getCompanyMap($admin_id);
        foreach ($company as $v) {
            $cid[] = $v['store_id'];
        }
        return $cid;
    }

    public function createNumber() {
        return strtoupper(uniqid('CN'));
    }
    
    public function getByStoreId($id){
        return $this->c->where('store_id='.$id)->find();
    }
    
    public function getStoreByNumber($company_number){
        return $this->c->where('company_number=\''.$company_number.'\'')->select();
    }

    public function getByAdminId($admin_id){
        $re = $this->m->get('company_map_' . $admin_id);
        if (!$re) {
            $re = $this->c->where(array('admin_id' => $admin_id))->find();
            $this->m->set('company_map_' . $admin_id, $re, true);
        }
        return $re;
    }

}
